package per.vic.attachment.autoconfigure;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import per.vic.attachment.controller.AttachmentController;
import per.vic.attachment.dao.AttachmentDao;
import per.vic.attachment.schedule.AttachmentCleaner;
import per.vic.attachment.service.AttachmentService;

/**
 * @description: 附件starter 入口
 * @author: Vic.xu
 * @date: 2019年12月12日 上午9:05:28
 */
@Configuration
@ConditionalOnClass(value = { JdbcTemplate.class })
@ConditionalOnWebApplication
@ConditionalOnExpression("${attachment.enabled:true}")
@EnableConfigurationProperties(AttachmentProperties.class)
public class AttachmentAutoconfigure implements InitializingBean {
	
	@Autowired 
	AttachmentProperties attachmentProperties;
	
	@Resource
	private AttachmentDao attachmentDao;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		checkAttachmentProperties();

	}
	
	/**
	 * 检测必须配置的参数项是否存在
	 */
	private void checkAttachmentProperties() {
		if(attachmentProperties.isCheckTable()) {
			Assert.state(attachmentDao.isAttachmentTableExist(), "请先为attachment-starter创建附件表");
		}
		Assert.notNull(attachmentProperties.getVisit(), "请配置附件访问的地址前缀attachment.visit,附件访问的地址根据id生成");
		Assert.notNull(attachmentProperties.getHost(), "请配置附件访问的主机attachment.host,附件访问的地址会重定向的到host+附件的相对地址");
		Assert.notNull(attachmentProperties.getPosition(), "请配置附件存储的位置attachment.position");
		Assert.notNull(attachmentProperties.getBroken(), "请问配置默认的附件的相对地址attachment.broken");
	}

	/**
	 * DAO
	 */
	@Bean
	@ConditionalOnMissingBean
	public AttachmentDao attachmentDao() {
		return new AttachmentDao();
	}

	/**
	 * service
	 */
	@Bean
	@ConditionalOnMissingBean
	public AttachmentService attachmentService() {
		return new AttachmentService();
	}

	/**
	 * cleaner
	 */
	@Bean
	@ConditionalOnMissingBean
	public AttachmentCleaner attachmentCleaner() {
		return new AttachmentCleaner();
	}

	/**
	 * controller
	 */
	@Bean
	@ConditionalOnMissingBean
	public AttachmentController attachmentController() {
		return new AttachmentController();
	}

}
